package com.lishui.wateroj.aspect;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 打印日志切面
 */
@Aspect
@Component
@Slf4j
@Order(1)
public class AutoLogAspect {

    @Pointcut("execution(* com.lishui.wateroj.controller.*.*(..)) && @annotation(io.swagger.annotations.ApiOperation)")
    public void autoLogPointcut() {}

    @Before("autoLogPointcut()")
    public void autoLogAdvice(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        ApiOperation annotation = signature.getMethod().getAnnotation(ApiOperation.class);
        String logMessage = annotation.value();
        Object[] args = joinPoint.getArgs();
        String reqParam = "[" + StringUtils.join(args, ", ") + "]";
        // 获取请求路径
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
        String url = httpServletRequest.getRequestURI();
        // 输出请求日志
        log.info("request start，path: {}, ip: {}, params: {}, message: {}", url,
                httpServletRequest.getRemoteHost(), reqParam, logMessage);
    }


}
